package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.VideoEditorEntry;
import com.stark.ve.core.IEditorListener;
import com.stark.ve.merge.MergeItem;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.VideoSpliceAdapter;
import flc.ast.databinding.ActivityVideoSpliceBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.ToastUtil;

public class VideoSpliceActivity extends BaseAc<ActivityVideoSpliceBinding> {

    public static String videoPath;
    private int selPosition;
    private List<String> listSplice = new ArrayList<>();
    private VideoSpliceAdapter spliceAdapter;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoSbLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_splice;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoSpliceBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.tvDeriveVideo.setOnClickListener(this);
        mDataBinding.ivGenerate.setOnClickListener(this);
        mDataBinding.ivVideoSpliceAdd.setOnClickListener(this);
        mDataBinding.rvVideoSpliceList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        spliceAdapter = new VideoSpliceAdapter();
        mDataBinding.rvVideoSpliceList.setAdapter(spliceAdapter);
        spliceAdapter.setOnItemClickListener(this);
        spliceAdapter.addChildClickViewIds(R.id.ivVideoSpliceItemSwap);
        spliceAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivVideoSpliceAdd:
                Intent intent = new Intent(mContext, SelVideoActivity.class);
                intent.putExtra(Content.Again, true);
                startActivityForResult(intent, Content.Request_split);
                break;
            case R.id.ivGenerate:
                mergeVideo();
                break;
            case R.id.tvDeriveVideo:
                saveVideo();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        selPosition=position;
        Intent intent = new Intent(mContext, SelVideoActivity.class);
        intent.putExtra(Content.Again, true);
        startActivityForResult(intent, Content.Request_replace);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoSpliceItemSwap:
                swapVideo(position, position + 1);
                break;
        }
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        listSplice.add(videoPath);
        spliceAdapter.setList(listSplice);
        //设置播放器
        setPlayer();
    }

    //临时保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到相册
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        },500);
                    }
                });
            }
        }, 1000);
    }

    private void mergeVideo() {
        if (listSplice.size() < 2) {
            ToastUtils.showShort(R.string.please_select_one);
            return;
        }
        List<String> resultSplitLists = new ArrayList<>();
        for (String path : listSplice) {
            resultSplitLists.add(path);
        }
        EditorHolder.editor().videoMerge(resultSplitLists, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                videoPath = outFilePath;
                videoLength = MediaUtil.getDuration(videoPath);
                mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
                mDataBinding.tvVideoSbRight.setText(TimeUtil.getMmss(videoLength));
                mDataBinding.videoView.setVideoPath(videoPath);
                mDataBinding.videoView.seekTo(1);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                mDataBinding.videoView.start();
                startTime();
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.splice_def));
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.splice_ing)
                        + progress
                        + getString(R.string.unit_percent));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
           if (requestCode == Content.Request_split){
               String path = (String) data.getSerializableExtra(Content.VideoPath);
               listSplice.add(0,path);
               spliceAdapter.clearPosition();
               spliceAdapter.setList(listSplice);
               spliceAdapter.notifyDataSetChanged();
           }else if (requestCode==Content.Request_replace){
               String path = (String) data.getSerializableExtra(Content.VideoPath);
               listSplice.set(selPosition,path);
               spliceAdapter.clearPosition();
               spliceAdapter.setList(listSplice);
               spliceAdapter.notifyDataSetChanged();
           }
        }
    }

    private void swapVideo(int preVideoPos, int nextVideoPos) {
        String prePath = listSplice.get(preVideoPos);
        listSplice.set(preVideoPos, listSplice.get(nextVideoPos));
        listSplice.set(nextVideoPos, prePath);
        spliceAdapter.clearPosition();
        spliceAdapter.setList(listSplice);
        spliceAdapter.notifyDataSetChanged();
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvVideoSbLeft.setText("00:00");
        mDataBinding.tvVideoSbRight.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoSbLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

}